import { defineStore } from 'pinia'

import $axios from '../tools/axios'

export const useMenuStore = defineStore('menu', {
  state: () => {
    return {
      isCollapse: false,
      menus: [],
      menus4me: [],
      menutree: [],
      menutree4me: [],
      // JavaScript中的Map
      sys: ['系统管理', '系统功能管理'],
      preticket: ['运营管理', '放票管理'],
      role: ['系统管理', '角色管理'],
      currentpath: 'sys'
    }
  },
  getters: {
    // // 响应路由的变化
    // getCrmbreadcrumbByPageName: (state) => {
    //   return (pagename) => state[pagename]
    // }
    getCrmbreadcrumbByPageName: (state) => state[state.currentpath]
  },
  actions: {
    buildMenuTree4Me() {
      this.menutree4me = []
      const root = this.menus4me.find((menu) => menu.presysid === 0)
      this.fillChildren(root)
      this.menutree4me[0] = root
    },
    setCurrentpath(to) {
      this.currentpath = to.name
    },
    getChildren4me(presysid) {
      return this.menus4me.filter((menu) => menu.presysid === presysid)
    },

    getChildren(presysid) {
      return this.menus.filter((menu) => menu.presysid === presysid)
    },

    /**
     * 填充root节点的孩子节点
     * @param {*} root
     */
    fillChildren(root) {
      if (root == null) return
      // 从menus中寻找root节点的所有孩子节点
      root.children = []
      for (let i = 0; i < this.menus.length; i++) {
        if (this.menus[i].presysid === root.sysid) {
          root.children.push(this.menus[i])
        }
      }
      for (let i = 0; root != null && root.children != null && i < root.children.length; i++) {
        this.fillChildren(root.children[i])
      }
    },

    /**
     * 转换List到Tree
     */
    buildMenuTree() {
      this.menutree = []
      const root = this.menus.find((menu) => menu.presysid === 0)
      this.fillChildren(root)
      this.menutree[0] = root
      console.log(this.menutree)
    },
    async loadAllByLists() {
      this.menus = []
      const path = '/sy/q/all/list'
      const { data: res } = await $axios.get(path)
      if (res.code === 200) {
        this.menus = res.data
        this.buildMenuTree()
      }
      console.log(this.menus)
    },
    async load4MeByLists() {
      const passenger = {
        rid: 1
      }
      sessionStorage.setItem('passenger', JSON.stringify(passenger))
      const s = sessionStorage.getItem('passenger')
      const p = JSON.parse(s)
      this.menus4me = []
      const path = '/sy/q/list/' + p.rid
      const { data: res } = await $axios.get(path)
      if (res.code === 200) {
        this.menus4me = res.data
      }
      console.log(this.menus4me)
    }
  }
})
